package cn.itcast.hotel.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            // 条件过滤构建
            buildBasicQuery(params, request);

            // 分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            SearchResponse res = client.search(request, RequestOptions.DEFAULT);
            // 排序 - 定位
            if (!StringUtils.isEmpty(params.getLocation())) {
                request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                    .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }
            // 结果
            return this.handleResponse(res);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            buildBasicQuery(params, request);
            request.source().size(0);
            buildAggregation(request);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> result = new LinkedHashMap<>(2);
            // 解析结果
            Aggregations aggregations = response.getAggregations();
            // 根据品牌名称获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("品牌", brandList);
            List<String> cityList = getAggByName(aggregations, "cityAgg");
            result.put("城市", cityList);
            List<String> starList = getAggByName(aggregations, "starAgg");
            result.put("星级", starList);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                SuggestBuilders.completionSuggestion("suggestion").prefix(prefix).skipDuplicates(true).size(10)));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 解析结果
            Suggest suggest = response.getSuggest();
            CompletionSuggestion completionSuggestion = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            // System.out.println(keyAsString + "=====>" + bucket.getDocCount());
            brandList.add(keyAsString);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        // 聚合条件
        request.source().aggregation(AggregationBuilders
            // 名称
            .terms("brandAgg")
            // 字段
            .field("brand")
            // 大小
            .size(100));
        request.source().aggregation(AggregationBuilders
            // 名称
            .terms("cityAgg")
            // 字段
            .field("city")
            // 大小
            .size(100));
        request.source().aggregation(AggregationBuilders
            // 名称
            .terms("starAgg")
            // 字段
            .field("starName")
            // 大小
            .size(100));
    }

    public void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字全文检索
        if (StringUtils.isEmpty(params.getKey())) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        // 城市
        if (!StringUtils.isEmpty(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // 品牌
        if (!StringUtils.isEmpty(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 星级
        if (!StringUtils.isEmpty(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        // 价格
        if (!ObjectUtils.isEmpty(params.getMinPrice()) && !ObjectUtils.isEmpty(params.getMaxPrice())) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));
        }
        // function - 算分控制 - 广告
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
            // 原始查询
            boolQuery,
            // function score的数组
            new FunctionScoreQueryBuilder.FilterFunctionBuilder[] {
                // 其中一个function score元素
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                    // 过滤条件
                    QueryBuilders.termQuery("isAD", true),
                    // 算分函数
                    ScoreFunctionBuilders.weightFactorFunction(10))});

        request.source().query(functionScoreQuery);
    }

    public PageResult handleResponse(SearchResponse res) {
        SearchHits hits = res.getHits();
        // 总条数
        long value = hits.getTotalHits().value;
        System.out.println("共搜索到" + value + "条数据");
        SearchHit[] searchHits = hits.getHits();
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            String sourceAsString = searchHit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            // 高亮结果
            // Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            // if (!CollectionUtils.isEmpty(highlightFields)) {
            // HighlightField field = highlightFields.get("name");
            // if (field != null) {
            // String name = field.getFragments()[0].toString();
            // hotelDoc.setName(name);
            // }
            // }
            // 距离 排序值
            Object[] sortValues = searchHit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            list.add(hotelDoc);
            // System.out.println(hotelDoc);
        }
        return new PageResult(value, list);
    }

    @Override
    public Boolean deleteById(Long id) {

        try {
            // request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            client.delete(request, RequestOptions.DEFAULT);
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean insertById(Long id) {
        try {
            // 查询酒店数据
            Hotel hotel = this.getById(id);
            // 转换为文档对应实体
            HotelDoc hotelDoc = new HotelDoc(hotel);

            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
